import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { Input } from 'antd';

const Captcha = forwardRef(({ onCaptchaChange }, ref) => {
  const [captcha, setCaptcha] = useState('');
  const [userInput, setUserInput] = useState('');

  // 暴露方法给父组件
  useImperativeHandle(ref, () => ({
    generateCaptcha,
    validate: () => userInput.toUpperCase() === captcha
  }));

  // 生成随机4位验证码（字母+数字）
  const generateCaptcha = () => {
    const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    let result = '';
    for (let i = 0; i < 4; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    setCaptcha(result);
    setUserInput('');
    onCaptchaChange(false);
    return result;
  };

  useEffect(() => {
    generateCaptcha();
  }, []);

  const handleInputChange = (e) => {
    const value = e.target.value.toUpperCase();
    setUserInput(value);
    onCaptchaChange(value === captcha);
  };

  return (
    <div className="captcha-container">
      <Input
        placeholder="请输入图形验证码"
        value={userInput}
        onChange={handleInputChange}
        maxLength={4}
        style={{ width: 200 }}
      />
      <div style={{ display: 'inline-block' }}>
        {captcha.split('').map((char, index) => (
          <span 
            key={index}
            
            style={{
              display: 'inline-block',
              transform: `rotate(${Math.random() * 20 - 10}deg)`,
              color: `rgb(${50 + Math.random() * 150}, 
                        ${50 + Math.random() * 150}, 
                        ${50 + Math.random() * 150})`,
              fontFamily: 'monospace',
              fontWeight: 'bold',
              fontSize: '24px',
              margin: '0 1px'
            }}
          >
            {char}
          </span>
        ))}
        <span 
          type="button" 
          onClick={generateCaptcha}
          className="refresh-btn"
          aria-label="刷新验证码"
        >
          🔄
        </span>
      </div>
    </div>
  );
});

export default Captcha;
